﻿using Elastic.Clients.Elasticsearch;
using Elastic.Transport;
using RuYiAdmin.Net.UniversalFoundation.Configurations;
using System;
using System.Collections.Generic;

namespace RuYiAdmin.Net.UniversalFoundation.Contexts
{
    /// <summary>
    /// ES NEST工具类
    /// </summary>
    public static class RuYiEsNestContext
    {
        /// <summary>
        /// Lazy对象
        /// </summary>
        private static readonly Lazy<ElasticsearchClient> LazyInstance = new Lazy<ElasticsearchClient>(() =>
        {
            var elasticClient = new ElasticsearchClient();

            if (RuYiGlobalConfig.ElasticsearchConfig.Uri.Contains(','))
            {
                var urls = new List<Uri>();
                foreach (var item in RuYiGlobalConfig.ElasticsearchConfig.Uri.Split(','))
                {
                    urls.Add(new Uri(item));
                }
                var connectionPool = new StaticNodePool(urls);//创建连接池

                var settings = new ElasticsearchClientSettings(connectionPool);//创建连接设置
                settings.DefaultIndex(RuYiGlobalConfig.ElasticsearchConfig.DefaultIndex);//设置默认索引
                if (!string.IsNullOrEmpty(RuYiGlobalConfig.ElasticsearchConfig.UserName) && !string.IsNullOrEmpty(RuYiGlobalConfig.ElasticsearchConfig.Password))
                {
                    settings.Authentication(new BasicAuthentication(RuYiGlobalConfig.ElasticsearchConfig.UserName, RuYiGlobalConfig.ElasticsearchConfig.Password));
                }
                elasticClient = new ElasticsearchClient(settings);
            }
            else
            {
                var settings = new ElasticsearchClientSettings(new Uri(RuYiGlobalConfig.ElasticsearchConfig.Uri));//创建连接设置
                settings.DefaultIndex(RuYiGlobalConfig.ElasticsearchConfig.DefaultIndex);//设置默认索引
                if (!string.IsNullOrEmpty(RuYiGlobalConfig.ElasticsearchConfig.UserName) && !string.IsNullOrEmpty(RuYiGlobalConfig.ElasticsearchConfig.Password))
                {
                    settings.Authentication(new BasicAuthentication(RuYiGlobalConfig.ElasticsearchConfig.UserName, RuYiGlobalConfig.ElasticsearchConfig.Password));
                }
                elasticClient = new ElasticsearchClient(settings);
            }

            return elasticClient;
        });

        /// <summary>
        /// 单例对象
        /// </summary>
        public static ElasticsearchClient Instance { get { return LazyInstance.Value; } }

        /// <summary>
        /// 是否已创建
        /// </summary>
        public static bool IsInstanceCreated { get { return LazyInstance.IsValueCreated; } }
    }
}
